package com.tyning.newcode.jz32_2;

/**
 * 剑指 Offer 32 - II. 从上到下打印二叉树 II
 * 从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。
 *
 *
 *
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回其层次遍历结果：
 *
 * [
 *   [3],
 *   [9,20],
 *   [15,7]
 * ]
 *
 *
 * 提示：
 *
 * 节点总数 <= 1000
 * https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/
 * 注意：本题与主站 102 题相同：https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 */

import com.tyning.utils.TreeNode;
import com.tyning.utils.TreeNodeUtil;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author haining
 */
public class Solution {

    public static void main(String[] args) {
        TreeNode treeNode = TreeNodeUtil.createTreeNode(new Integer[]{3,9,20,null,null,15,7});
        Solution solution = new Solution();
        solution.levelOrder(treeNode);
    }

    class Pair<T, K> {
        T t;
        K k;

        public Pair(T t, K k) {
            this.t = t;
            this.k = k;
        }

        public T getT() {
            return t;
        }

        public K getK() {
            return k;
        }
    }

    List<List<Integer>> list = new ArrayList<>();
    Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        queue.add(new Pair<>(root, 0));
        setList(queue);
        return list;
    }

    public void setList(Queue<Pair<TreeNode, Integer>> queue) {
        if (queue.isEmpty()) {
            return;
        }
        Pair<TreeNode, Integer> rootMap = queue.poll();
        TreeNode root = rootMap.getT();
        Integer listKey = rootMap.getK();
        List<Integer> listlist = listKey.intValue() >= list.size() ? null : list.get(listKey.intValue());
        if (listlist == null) {
            list.add(listKey.intValue(), new ArrayList<>());
            listlist = list.get(listKey);
        }
        listlist.add(root.val);
        if (root.left != null) {
            queue.add(new Pair<>(root.left, listKey + 1));
        }
        if (root.right != null) {
            queue.add(new Pair<>(root.right, listKey + 1));
        }
        setList(queue);
    }


}
